package com.econ.ribbon;

import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.*;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.List;

/**
 * @Author : zjf
 * @Description : 使用ip做ribbon的负载均衡策略
 * @Date : 2023/7/25 14:36
 * @Modified by : zjf
 */
@Slf4j
public class IpUserHashRule extends AbstractLoadBalancerRule {

    @Override
    public void initWithNiwsConfig(IClientConfig clientConfig) {

    }

    @SneakyThrows
    @Override
    public Server choose(Object key) {
        return choose(getLoadBalancer(), key);
    }

    public Server choose(ILoadBalancer lb, Object key) throws UnknownHostException{
        if (lb==null){
            return null;
        }else {
            Server server = null;
            while (server==null){
                //获取可用的服务实例列表
                List<Server> upList = lb.getReachableServers();
                int serverCount = upList.size();
                if(serverCount == 0){
                    return null;
                }
                int i=ipAddressHash(serverCount);
                server = upList.get(i);
                log.info("feign调用console中方法的host:" + server.getHost());
            }
            return  server;
        }
    }

    private int ipAddressHash(int serverCount) {
        try {
            InetAddress address = InetAddress.getLocalHost();
            String ipv6 = address.getHostAddress();
            log.info("获取的ipv6值为:" + ipv6);
            int code = Math.abs(ipv6.hashCode());
            return code%serverCount;
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return 0;
    }

}
